<?php

require_once ('ICartService.php');
require_once ('BaseService.php');
require_once 'util/ServiceUtil.php';
require_once 'util/StringUtil.php';
require_once 'dao/CartDao.php';

class CartService extends BaseService implements ICartService 
{
	
	public static $NAME = "CartService";
	protected $cart;
	public function CartService() 
	{
		$this->cart = new CartDao();
		$this->initializeDB();
	}
	
	public function create(CartDao $object) 
	{
		if($object)
		{
			try 
			{
				$this->sql = "INSERT INTO cart(pid,quantity) VALUES('$object->pid','$object->quantity')";
				$this->query = mysql_query($this->sql,$this->myDb);
				return $this->checkQueryResult(mysql_affected_rows($this->myDb));
			}catch (Exception $exc)
			{
				return $exc;
			}
			
		}
		return NULL;
	}
	
	public function delete($id) 
	{
		if($id)
		{
			try
			{
				$this->sql = "DELETE * FROM cart WHERE id='$id'";
				$this->query = mysql_query($this->sql,$this->myDb);
				return $this->checkQueryResult(mysql_affected_rows($this->myDb));
			}catch(Exception $exc)
			{
				return $exc;
			}
		}
		return NULL;
	}
	
	public function read($id) 
	{
		
		if($id==NULL||$id==-1)
		{
			$this->sql = "SELECT * FROM cart";
		}else
		{
			$this->sql = "SELECT * FROM cart WHERE id='$id'";
		}
		try 
		{
			$this->query = mysql_query($this->sql,$this->myDb);
			$this->numRows = mysql_num_rows($this->query);
			for($i=0;$i<$this->numRows;$i++)
 			{
 				$row = mysql_fetch_object($this->query);
 				
 				$this->cart->id = $row->id;
				$this->cart->pid = $row->pid;
				$this->cart->quantity = $row->quantity;
				$this->cart->time = $row->time;
				
				$this->result[] = $this->cart;
 			}
			return $this->result;
		}catch (Exception $exc)
		{
			return $exc;
		}
		return NULL;
	}
	
	public function update(CartDao $object) 
	{
		if($object)
		{
			try 
			{
				$this->sql = "UPDATE TABLE cart SET cart.pid = '$object->pid',
							 cart.quantity = '$object->quantity'";
				$this->query = mysql_query($this->query,$this->myDb);
				return $this->checkQueryResult(mysql_affected_rows($this->myDb));
			}catch (Exception $exc)
			{
				return $exc;
			}
		}
		return NULL;
	}
	
}
?>